#!/usr/bin/env python
# -*- coding:utf-8 -*-
# fileName: sendHttpReq.py

import json
import requests
import os
from util.getAPIInfo import GetAPIInfo
from util.md5Enceyprion import Md5Encryption
from util.readYaml import ReadYaml
from util.getlog import get_log
from configs import globalVariables
'''
【功能】： 
1. 对header进行md5加密处理
2. 发送一个http请求
【入参】：
http请求的接口信息-url，method，request body,headers
【返回值】：
http请求的response body
'''
read_token = {}
class SendHttpReq(object):
    # header加密处理：给Cookie和x-param-key赋值
    def deal_header_json(self, headers,data):
        global read_token
        # log.info("加密前的headers： %s" % headers)
        # 给request body 加密，获得autograph作为x-param-key的值
        autograph = Md5Encryption().getAutograph(data)
        headers['x-param-key'] = autograph

        # access_token.yml中的access_token，作为cookie的值
        if len(read_token) <= 0:
            curPath = os.path.abspath(os.path.dirname(__file__))
            tokenPath = os.path.abspath(os.path.dirname(curPath) + os.path.sep + "configs/access_token.yml")
            read_token = ReadYaml().readYaml(tokenPath)
        access_token = read_token['access_token']
        headers['X-LONGCHAT-Token'] = access_token

        # globalVariables.logger.info("加密后的headers： %s" % headers)
        return headers

    def deal_header_notjson(self, headers):
        global read_token
        # access_token.yml中的access_token，作为cookie的值
        if len(read_token) <= 0:
            curPath = os.path.abspath(os.path.dirname(__file__))
            tokenPath = os.path.abspath(os.path.dirname(curPath) + os.path.sep + "configs/access_token.yml")
            read_token = ReadYaml().readYaml(tokenPath)
        access_token = read_token['access_token']
        headers['X-LONGCHAT-Token'] = access_token

        # globalVariables.logger.info("加密后的headers： %s" % headers)
        return headers

    def sendHttpReq(self, method, url, headers, data=None,files=None):
        # 忽略不安全的请求警告信息
        requests.packages.urllib3.disable_warnings()
        requests.adapters.DEFAULT_RETRIES = 5
        # s = requests.sessions()
        # s.keep_alive = False  # 关闭多余连接
        '''---old---
        if isinstance(data,dict):
            data = json.dumps(data, sort_keys=True, indent = 4)
        # print('data',data)
        if method == "Post" or "POST":
            headers = self.deal_header(headers,data)
            try:
                # 遇到requests的ssl验证，若想直接跳过不验证，设置verify=False即可
                response = requests.post(url=url, headers=headers, data=data, verify=False)
            except Exception as e:
                log.error("发送post请求出错~ %s" % e)
        elif method == "Get" or "GET":
            try:
                response = requests.get(url=url, headers=headers, verify=False)
            except Exception as e:
                log.error("发送get请求出错~ %s" % e)
        log.info("response body is: %s" % response.json())
        return response.json()
        '''

        if method == "Post" or "POST":
            if 'Content-Type' in list(headers.keys()): # 非文件上传类request
                if (headers['Content-Type']).find('application/json') >= 0:  # 处理application/json request
                    if isinstance(data, dict):
                        data = json.dumps(data, sort_keys=True, indent=4)  # 将字典格式转换为json格式
                    headers = self.deal_header_json(headers, data)
                    try:
                        # 遇到requests的ssl验证，若想直接跳过不验证，设置verify=False即可
                        response = requests.post(url=url, headers=headers, verify=False, data=data)
                    except Exception as e:
                        globalVariables.logger.error("发送post请求出错~ %s" % e)
            elif files is not None: # 文件上传类request (注：上传文件的request，headers中不要传Content-Type)
                headers = self.deal_header_notjson(headers)
                try:
                    # 遇到requests的ssl验证，若想直接跳过不验证，设置verify=False即可
                    print('````````````````````````````',headers)
                    print('````````````````````````````', files)
                    print('````````````````````````````', data)
                    response = requests.post(url=url, headers=headers, data = data, files=files)
                except Exception as e:
                    globalVariables.logger.error("发送post请求出错~ %s" % e)

        elif method == "Get" or "GET":
            try:
                response = requests.get(url=url, headers=headers, verify=False)
            except Exception as e:
                globalVariables.logger.error("发送get请求出错~ %s" % e)

        try:
            globalVariables.logger.info("response body is: %s" % response.json())
            return response.json()
        except Exception as e:
            globalVariables.logger.info("response.status_code is: %s" % response.status_code)
            return response.status_code

if __name__ == "__main__":
    apiInfo = GetAPIInfo().getAPISendInfo('getCourseInfoList','api_trainingAndExam.yml')
    print('apiInfo',apiInfo)

    run = SendHttpReq()
    res = run.sendHttpReq(apiInfo['method'], apiInfo['url'], apiInfo['headers'], apiInfo['data'])
    # print(type(res))
    print(res)
